package cn.net.xyan.easy.spring.jpa.config;


import cn.net.xyan.easy.spring.core.config.AutoConfigManagerFactory;
import cn.net.xyan.easy.spring.core.config.IAutoConfigManager;
import cn.net.xyan.easy.spring.core.utils.JsonHelper;
import cn.net.xyan.easy.spring.jpa.support.EasyJpaRepositoryImpl;
import cn.net.xyan.easy.spring.jpa.support.EnableEasyJpaRepositories;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import java.util.Properties;
import java.util.Set;

/**
 * Created by xiashenpin on 15/11/8.
 */
@Configuration("cn.net.xyan.easy.spring.jpa.config.JPAConfiguration")
@ComponentScan(basePackages = {"cn.net.xyan.easy.spring.jpa.utils"})
@EnableTransactionManagement
@EnableEasyJpaRepositories(
        transactionManagerRef = "transactionManager",
        entityManagerFactoryRef = "entityManagerFactory",
        repositoryBaseClass = EasyJpaRepositoryImpl.class
)
public class JPAConfiguration {

    private @Value("${hibernate.databasePlatform}") String databasePlatform;

    private @Value("${hibernate.ejb.naming_strategy}") String name_strategy;
    private @Value("${hibernate.show_sql}")            String show_sql;
    private @Value("${hibernate.hbm2ddl.auto}")        String hbm2ddl_auto;
    private @Value("${hibernate.packagesToScan}")      String packagesToScan;

    Logger logger = LoggerFactory.getLogger(JPAConfiguration.class);

    @Autowired
    ApplicationContext context;


    @Bean
    public HibernateJpaVendorAdapter hibernateJpaVendorAdapter(){
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter =   new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setDatabasePlatform(databasePlatform);
        return hibernateJpaVendorAdapter;
    }


    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource,HibernateJpaVendorAdapter hibernateJpaVendorAdapter)
    {
        if (packagesToScan==null)
            packagesToScan = "";
        String[] packages = packagesToScan.split(";");

        Set<String> autoConfigModelPackages = AutoConfigManagerFactory.autoConfigManager().readValue(IAutoConfigManager.EntityScanPackagesKey, JsonHelper.StringSet);

        for (String packageName : packages){
            autoConfigModelPackages.add(packageName);
        }

        packages = autoConfigModelPackages.toArray(new String[0]);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

        factory.setDataSource(dataSource);
        factory.setJpaVendorAdapter(hibernateJpaVendorAdapter);


        factory.setPackagesToScan(packages);

        Properties jpaProperties = new Properties();
        jpaProperties.put("hibernate.ejb.naming_strategy", name_strategy);
        jpaProperties.put("hibernate.show_sql", show_sql);
        jpaProperties.put("hibernate.hbm2ddl.auto", hbm2ddl_auto);
        factory.setJpaProperties(jpaProperties);

        factory.afterPropertiesSet();
        factory.setLoadTimeWeaver(new InstrumentationLoadTimeWeaver());
        return factory;
    }


    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory factory)
    {
        //EntityManagerFactory factory = localContainerEntityManagerFactoryBean.getObject();
        return new JpaTransactionManager(factory);
    }

}
